<!-- 电站列表 -->
<template>
	<uv-navbar :fixed="false" :title="title" left-arrow @leftClick="$onClickLeft" rightText="新建" rightIcon="plus"
		@rightClick="rightClick">
	</uv-navbar>
	<view class="container">
		<view class="bg-white">
			<uv-radio-group v-model="radio" @change="onChange" labelColor="#646464">
				<uv-radio v-for="tab in tabList" :key="tab.type" :name="tab.name"
					:customStyle="{margin: '8px'}">{{tab.name}}</uv-radio>
				<!-- <uv-radio name="计划" :customStyle="{margin: '8px'}">计划</uv-radio> -->
			</uv-radio-group>

			<uv-drop-down v-if="radio == '工单'" ref="dropDown" sign="dropDown_2" text-active-color="#3c9cff"
				:extra-icon="{name:'arrow-down-fill',color:'#666',size:'26rpx'}"
				:extra-active-icon="{name:'arrow-up-fill',color:'#3c9cff',size:'26rpx'}"
				:custom-style="{padding: '0 30rpx'}" @click="selectMenu">
				<uv-drop-down-item name="order" type="2" :label="currentType.label" :value="currentType.value">
				</uv-drop-down-item>

			</uv-drop-down>
			<uv-drop-down-popup sign="dropDown_2" :click-overlay-on-close="true" :currentDropItem="currentDrop"
				@clickItem="clickItem" @popupChange="dropChange"></uv-drop-down-popup>
		</view>
		<view class="orders-list d-flex flex-column w-100" style="padding: 20rpx; padding-bottom: 0;">

			<uv-empty v-if="!showData" mode="list"></uv-empty>
			<scroll-view class="list"
				style="height: {{viewHeight - windowHeight - 90 - mainHeight}}px;margin-top:{{mainHeight}}px" v-else
				enable-back-to-top="true" :refresher-enabled="false" refresher-default-style="black"
				:refresher-triggered="refresher" bindrefresherrefresh="bindrefresherrefresh" scroll-y="true"
				bindscrolltolower="loadData" @refresherrefresh="onRefresh" >

				<!-- 计划的数据 -->
				<template v-if="radio == '计划'">
					<uv-cell-group v-for="(item, index) in planList" :key="index">
						<view class="title">
							<uv-cell icon="" :title="item.planTitle" value="查看" :border="false" :isLink="true"
								arrow-direction="right" @click="navigateToPlan(item)"></uv-cell>

						</view>
						<uv-cell center title="计划开始处理时间：" :value="item.startTime" />
						<uv-cell center title="重复方式：" class="cus-cell">
							<!-- 自定义右侧值 -->
							<template v-slot:value>
								<!-- 已完成 -->
								<text class="iconfont icon-yk_yuanquan_fill"
									style="color: #41d068;font-size: 20rpx;margin-right: 6rpx;"></text>

								<uv-icon style="margin-left: 10rpx;font-size: 34rpx;" name="arrow-down" data-type="open"
									v-if="!showPlanCollapse[index]" @click="handlePlanCollapse(index)" />
								<uv-icon style="margin-left: 10rpx;font-size: 34rpx;" name="arrow-up" data-type="close"
									v-if="showPlanCollapse[index]" @click="handlePlanCollapse(index)" />
							</template>

						</uv-cell>
						<uv-cell center title="重复次数：" v-if="showPlanCollapse[index]" :value="item.ruleExecNum" />
						<uv-cell center title="已生成：" v-if="showPlanCollapse[index]" :value="item.ruleAlreadyExecNum" />
						<uv-cell center title="下次生成时间：" v-if="showPlanCollapse[index]" :value="item.nextGenTime" />
						<uv-cell center title="最后更新时间：" v-if="showPlanCollapse[index]" :value="item.updatedTime" />
						<uv-cell center title="最后更新人：" v-if="showPlanCollapse[index]" :value="item.userName" />
					</uv-cell-group>

				</template>

				<!-- 工单的数据 -->
				<template v-else-if="radio == '工单'">

					<uv-cell-group v-for="(item,index) in gongdanList" :key="item.id" class="cus-cell-group">
						<view class="title">
							<uv-cell center :title="item.title" value="查看" :border="false">
								<!-- 自定义右侧值 -->
								<template v-slot:value>
									<text @click="navigateToGongdan(item)">查看</text>
								</template>
							</uv-cell>
						</view>
						<uv-cell center title="状态：" class="cus-cell">
							<!-- 自定义右侧值 -->
							<template v-slot:value>
								<!-- 自定义状态展示icon -->
								<view calss="iconfont icon-yk_yuanquan_fill" :style="getStatusIconStyle(item.state)">
								</view>
								<!-- 使用条件判断设置内容 -->
								<text>{{ getStatusText(item.state) }}</text>
								<uv-icon style="margin-left: 10rpx;font-size: 34rpx;" name="arrow-down" data-type="open"
									v-if="!showCollapse[index]" @click="handleCollapse(index)" />
								<uv-icon style="margin-left: 10rpx;font-size: 34rpx;" name="arrow-up" data-type="close"
									v-if="showCollapse[index]" @click="handleCollapse(index)" />
							</template>

						</uv-cell>
						<uv-cell center title="编号：" v-if="showCollapse[index]" :value="item.number" />
						<uv-cell center title="所属电站：" v-if="showCollapse[index]" :value="item.powerstationName" />
						<uv-cell center title="设备：" v-if="showCollapse[index]" :value="item.deviceName" />

						<uv-cell center title="超时状态：" v-if="showCollapse[index]">
							<!-- 使用条件判断设置内容 -->
							<view v-if="item.outState === 0">未超时</view>
							<view v-if="item.outState === 1">已超时</view>
						</uv-cell>
						<uv-cell center title="超时时长：" :value="item.timeoutHour" v-if="showCollapse[index]" />
						<uv-cell center title="发起人：" :value="item.creater.userName" v-if="showCollapse[index]" />
						<uv-cell center title="发起时间：" :value="item.createdTime" v-if="showCollapse[index]" />
						<uv-cell center title="处理人：" :value="item.processor.userName" v-if="showCollapse[index]" />
						<uv-cell center title="计划处理时间：" v-if="showCollapse[index]">
							<view>{{item.planStartTime === null? '': item.planStartTime}} </view>
							<view>{{item.planEndTime === null? '': item.planEndTime}}</view>
						</uv-cell>
						<uv-cell center title="计划用时(h)：" :value="item.planTime" v-if="showCollapse[index]" />
						<uv-cell center title="实际处理时间：" v-if="showCollapse[index]">
							<view>{{item.realityStartTime === null? '': item.realityStartTime}}</view>
							<view>{{item.realityEndTime === null? '': item.realityEndTime}}</view>
						</uv-cell>
						<uv-cell center title="实际用时(h)：" :value="item.realityTime === null? '': item.realityTime"
							v-if="showCollapse[index]" />
						<uv-cell center title="验证人：" :value="item.validator.userName" v-if="showCollapse[index]" />
						<uv-cell center title="偏差字段：" :value="item.deviation" v-if="showCollapse[index]" />
					</uv-cell-group>
				</template>
			</scroll-view>

		</view>

	</view>
</template>


<script setup>
	import {
		ref,
		computed,
		reactive,
		onMounted,
		getCurrentInstance
	} from 'vue'
	import {
		useMainStore
	} from '@/store/store'
	import {
		storeToRefs
	} from 'pinia'
	import {
		onLoad,
		onPullDownRefresh,
		onReachBottom
	} from '@dcloudio/uni-app'
	import {
		formatDateTime,
		kmUnit
	} from '@/utils/util'
	import {
		orderGetOrders,
		orderReceive
	} from '@/api/order'
	import {
		reqWorksList,
		reqPlanList,
		reqPlanDetail
	} from "@/api/operate"
	const main = useMainStore()
	const {
		isLogin
	} = storeToRefs(main)
	const title = ref('运维管理')
	//状态配置映射
	const STATUS_CONFIG = {
		0: {
			text: '待接受',

			bgColor: '#f8b51e'
		},
		1: {
			text: '待处理',
			bgColor: '#f8b51e'
		},
		2: {
			text: '执行中',
			bgColor: '#048fff'
		},
		3: {
			text: '待验证',
			bgColor: '#f8b51e'
		},
		5: {
			text: '已完成',
			bgColor: '#41d068'
		},
		6: {
			text: '拒绝接受',
			bgColor: '#d81e06'
		},
		8: {
			text: '已终止',
			bgColor: '#d81e06'
		}
	}
	const page = ref(1)
	const pageSize = ref(10)
	const orders = ref([])
	const showData = ref(true)
	const refresher = ref(false)
	const showCollapse = ref([]) //是否折叠工单除 状态,名称 外的所有的数据
	const showPlanCollapse = ref([])
	const allTabList = ref([{
		type: 0,
		name: '工单',
	}, {
		type: 1,
		name: '计划',
	}, ])
	const modules = ref(null)
	const gongdanList = ref([])
	const planList = ref([])
	const radio = ref('工单')

	const current = ref(0)
	const type = ref(-1)
	const currentType = ref({
		label: '全部类型',
		value: null
	})
	const queryParams = reactive({
		"pageNum": 1,
		"pageSize": 10,
		"isPagination": true,
		"orderBy": "create_time desc",
		"orderByMap": {
			"createdTime": 0
		},
		"queryObj": {
			"powerStation": "",
			"name": "",
			"equipment": "",
			"beginTime": "",
			"endTime": "",
			"grade": "",
			"alState": "",
			"modules": "",
			"dzId": null
		}
	})
	const currentDrop = ref({
		label: '文档格式',
		value: 'all',
		activeIndex: 0,
		color: '#333',
		activeColor: '#2878ff',
		child: [{
				label: '全部类型',
				value: null
			},
			{
				label: '待接受',
				value: 0
			},
			{
				label: '待处理',
				value: 1
			},
			{
				label: '执行中',
				value: 2
			},
			{
				label: '待验证',
				value: 3
			},
			{
				label: '已完成',
				value: 5
			},
			{
				label: '拒绝接受',
				value: 6
			},
			{
				text: '已终止',
				value: 8
			},
		]
	})

	onLoad(() => {
		// if(!isLogin.value) {
		// 	uni.navigateTo({url: '/pages/components/pages/login/login'})
		// }

		const instance = getCurrentInstance().proxy
		const eventChannel = instance.getOpenerEventChannel()
		eventChannel.on('getModelId', (data) => {
			modules.value = data.modelId
			getOrders(radio.value, true)
		})
	})


	// 根据modelId动态计算显示的选项卡
	const tabList = computed(() => {
		// modules为13时只显示工单
		if (modules.value == 1 || modules.value == 3) {
			return allTabList.value.filter(tab => tab.type == 0)
		}
		// modules为25时显示全部
		else if (modules.value == 2 || modules.value == 5) {
			return allTabList.value
		}
		// 默认情况（可选）
		return []
	})
	//根据状态返回对应样式
	const getStatusIconStyle = (state) => {
		const config = STATUS_CONFIG[state] || {}
		return {
			backgroundColor: config.bgColor || 'transparent',
			width: config.bgColor ? '20rpx' : 'auto',
			height: config.bgColor ? '20rpx' : 'auto',
			borderRadius: config.bgColor ? '50%' : '0',
			fontSize: '20rpx',
			marginRight: '6rpx'

		}
	}
	// 获取状态文本
	const getStatusText = (state) => {
		return STATUS_CONFIG[state]?.text || ''
	}
	const loadData = () => {
		console.log("加载zhong...")
	}
	// 下拉刷新
	const onRefresh = () => {
		console.log("加载zhong999...")
		refresher.value = true; // 显示刷新动画
		// 模拟异步加载
		setTimeout(() => {
			refresher.value = false; // 隐藏动画
		}, 1000);
	}
	// 上拉加载
	const loadMore = () => {
		console.log("加载zhong111...")
	}
	const bindrefresherrefresh = () => {
		console.log("刷新zhong...")
		refresher.value = true; // 显示刷新动画
		// 模拟异步加载
		setTimeout(() => {
			refresher.value = false; // 隐藏动画
		}, 1000);
	}
	// 点击工单的折叠
	const handleCollapse = (index) => {
		console.log(event, 'event');
		// const index = event.currentTarget.dataset.index; // 获取点击的索引值
		// const {
		//   showCollapse
		// } = this.data;
		showCollapse.value[index] = !showCollapse.value[index]; // 切换展开状态

	}
	const handlePlanCollapse = (index) => {
		console.log("index==计划", index)
		showPlanCollapse.value[index] = !showPlanCollapse.value[index]; // 切换展开状态
	}
	//新建
	const rightClick = () => {
		uni.navigateTo({
			url: "/pages/components/pages/yunwei/createOrder"
		})
	}
	//选中下拉选项
	const clickItem = (e) => {
		// 下面有重新赋值，所以用let
		let {
			label,
			value
		} = e;
		currentType.value = {
			...e
		}
		getOrders(radio.value, true, value)
	}
	// 根据工单状态跳转至对应页面
	const navigateToGongdan = (e) => {
		console.log(e, 'eeeee');
		// <!-- 工单状态 0 待接受 1 待处理 2 执行中 3 待验证 4 待评价 5 已完成 6 拒绝接受 7 已撤销 8 终止 -->
		let type = e.state
		let id = e.id
		if (type === 0 || type === 6 || type === 8) {
			uni.navigateTo({
				url: `/pages/components/pages/yunwei/detail?id=${id}`,
			})
		} else if (type === 1 || type === 2 || type === 3 || type === 5) {
			uni.navigateTo({
				url: `/pages/components/pages/yunwei/detail?id=${id}`,
			})
			// uni.navigateTo({
			// 	url: `/pages/components/pages/yunwei/handleDetail?id=${id}`,
			// })
		}

	}
	const navigateToPlan = async (e) => {
		console.log("跳转工单", e)
		uni.navigateTo({
			url: "/pages/components/pages/scoreproduct/orderDetail?id=" + e.id
		})

	}
	//dropDown下拉选项
	const dropChange = (e) => {}
	onPullDownRefresh(() => {
		uni.stopPullDownRefresh()
	})
	//切换
	const onChange = (e) => {
		console.log("工单切换==", e)
		getOrders(e, true)

	}


	onReachBottom(() => {
		getOrders(radio.value, false)
	})
	/**
	 * 点击每个筛选项回调
	 * @param {Object} e { name, active, type } = e
	 */
	const selectMenu = (e) => {
		const {
			name,
			active,
			type
		} = e;
	}

	const getOrders = async (type, isRefresh = false, status) => {
		uni.showLoading({
			title: '加载中'
		})

		const map = {

		}
		let res = null;
		if (isRefresh) {
			gongdanList.value = []
			planList.value = []
			queryParams.pageNum = 1
		}
		// console.log("modules===", modules.value)
		if (type == '工单') {
			queryParams.queryObj.state = status
			queryParams.queryObj.modules = modules.value
			res = await reqWorksList(queryParams);
		} else if (type == '计划') {
			res = await reqPlanList(queryParams);
		}
		console.log("进来了", res)

		let orderData = res.data.data.list

		if (orderData && orderData.length > 0) {
			if (type == '工单') {
				gongdanList.value = gongdanList.value.concat(orderData)
			} else if (type == '计划') {
				planList.value = planList.value.concat(orderData)
				console.log("获取工单列表", orderData, planList.value)
			}

			queryParams.pageNum += 1
		}
		uni.stopPullDownRefresh();
		uni.hideLoading()
	}
	const detail = (id) => {
		uni.navigateTo({
			url: '/pages/components/pages/orders/detail?id=' + id
		})
	}

	onMounted(() => {
		// getOrders(radio.value, true)
	})
</script>

<style lang="scss" scoped>
	.left-margin {
		margin-left: 10rpx;
	}

	.container {
		.bg-white {
			.uv-radio-group {
				justify-content: space-around;
			}

			::v-deep {
				.uv-drop-down {
					justify-content: center;
					border-top: 1px solid #f0f0f3;
				}
			}

		}

		.orders-list {
			.list {
				.uni-scroll-view {
					::v-deep {
						.iconfont {
							position: relative;
							display: inline-block;
							width: 20rpx;
							/* 宽度 */
							height: 20rpx;
							/* 高度 */
							background-color: #000;
							/* 背景颜色，这里是黑色 */
							border-radius: 50%;
							/* 边框半径设置为50%，使得正方形变成圆形 */
						}

						.uv-cell-group {
							margin: 20rpx 0 !important;
						}
					}
				}
			}
		}
	}
</style>